﻿using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static BW.Mes.WinForms.BasicData.WorkshopForm;

namespace BW.Mes.WinForms.BasicData
{
    public partial class AddLineForm : XtraForm
    {
        private readonly HttpClient _httpClient;
        private readonly string _apiBaseUrl = "https://localhost:7274";

        public AddLineForm()
        {
            InitializeComponent();
            var handler = new HttpClientHandler
            {
                ServerCertificateCustomValidationCallback = (req, cert, chain, errors) => true
            };
            _httpClient = new HttpClient(handler);
            this.Load += AddLineForm_Load;
        }

        private async void AddLineForm_Load(object sender, EventArgs e)
        {
            await LoadWorkshops();
        }

        private async Task LoadWorkshops()
        {
            try
            {
                HttpResponseMessage response = await _httpClient.GetAsync($"{_apiBaseUrl}/api/Workshop/GetWorkshop");
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();
                var jsonObject = Newtonsoft.Json.Linq.JObject.Parse(responseBody);
                if (jsonObject["pageDatas"] != null)
                {
                    string dataJson = jsonObject["pageDatas"].ToString();
                    var workshops = JsonConvert.DeserializeObject<List<WorkShopModel>>(dataJson);

                    lookUpEditWorkshop.Properties.DataSource = workshops;
                    lookUpEditWorkshop.Properties.DisplayMember = "WorkshopName";
                    lookUpEditWorkshop.Properties.ValueMember = "Id";

                    // 配置下拉框，只显示车间名称
                    lookUpEditWorkshop.Properties.Columns.Clear();
                    lookUpEditWorkshop.Properties.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("WorkshopName", "车间名称"));
                    lookUpEditWorkshop.Properties.NullText = "请选择所属车间";
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载车间数据失败: {ex.Message}", "错误");
            }
        }

        private async void btnOK_Click(object sender, EventArgs e)
        {
            if (lookUpEditWorkshop.EditValue == null)
            {
                XtraMessageBox.Show("请选择一个所属车间。");
                return;
            }

            var model = new
            {
                LineCode = textEditLineCode.Text,
                LineName = textEditLineName.Text,
                LineMsg = textEditLineMsg.Text,
                WorkshopId = (long)lookUpEditWorkshop.EditValue,
                CreatedBy = "wyj" // 添加后端需要的CreatedBy字段
            };

            try
            {
                var json = JsonConvert.SerializeObject(model);
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                var response = await _httpClient.PostAsync($"{_apiBaseUrl}/api/Line/AddLine", content);

                if (response.IsSuccessStatusCode)
                {
                    XtraMessageBox.Show("添加成功！");
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
                else
                {
                    string errorContent = await response.Content.ReadAsStringAsync();
                    XtraMessageBox.Show($"添加失败：{response.ReasonPhrase} - {errorContent}");
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"提交数据时出错: {ex.Message}", "错误");
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void AddLineForm_Load_1(object sender, EventArgs e)
        {

        }

        private void lookUpEditWorkshop_EditValueChanged(object sender, EventArgs e)
        {

        }
    }
}